<?php


namespace app\admin\controller\jizhan;


use app\admin\model\HtnsBasestationStore;
use app\admin\model\HtnsExpress;
use app\admin\model\HtnsOrder;
use app\admin\model\HtnsOrderCartInfo;
use app\admin\model\HtnsOrderRefund;
use app\admin\model\HtnsOrderStatus;
use app\admin\model\HtnsProduct;
use app\admin\model\HtnsUser;
use app\admin\traits\Curd;
use app\admin\traits\HtnsTrait;
use app\api\services\HtnsApiService;
use app\api\services\OrderCartInfoService;
use app\api\services\OrderService;
use app\api\services\RefundOrderService;
use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use jianyan\excel\Excel;
use think\App;
use think\Exception;
use think\facade\Cache;

/**
 * Class Admin
 * @package app\admin\controller\system
 * @ControllerAnnotation(title="基站线下订单")
 */
class StoreOrder extends AdminController
{

    use Curd;
    use HtnsTrait;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new HtnsOrder();
        $htnsProduct = new HtnsProduct();

        $this->assign('payType', $this->model->payType);
        $this->assign('orderStatus', $this->model->status);
        $this->assign('orderTypes', $this->model->orderTypes);
        $this->assign('hcname', $htnsProduct->hcName);
        // 下单基站
//        $htnsBasestationStore = HtnsBasestationStore::select()->order('id desc')->toArray();
//        $storeList            = array_column($htnsBasestationStore, 'name', 'id');
//
        $htnsBasestationStore = new HtnsBasestationStore();
        $storeId = session('admin')['store_id'];//当前用户门店id
        $storeList            = $htnsBasestationStore->getStoreNameZz($storeId);
//        halt($storeList);
        $htnsOrderRefund = new HtnsOrderRefund();
        $refundStatus = $htnsOrderRefund->getRefundStatus();
        $this->assign('storeList', $storeList);
        $this->assign('refundStatus', $refundStatus);
    }

    /**
     * @NodeAnotation(title="列表")
     */
    public function index($export = 0)
    {
        $tab = input('tab');
//        $tabVal = $_COOKIE['tabValStoreOrder'];
        $storeId = session('admin')['store_id'];//当前用户门店id
        if ($this->request->isAjax() || $export || $tab) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();
            // 自定义搜索条件解析
            $whereArr = [];
            $filter   = input('filter');
            $filter = htmlspecialchars_decode($filter);// html特殊字符转化&quot;转换为'
            if ($filter) {
                $filterArr = json_decode($filter, true);
                if (isset($filterArr['hcname'])) {
                    $whereArr[] = ['erp_id', '=', $filterArr['hcname']];
                }
                if (isset($filterArr['id'])) {
                    $whereArr[] = ['id', '=', $filterArr['id']];
                }
                if (isset($filterArr['order_id'])) {
                    $whereArr[] = ['order_id', '=', $filterArr['order_id']];
                }
                if (isset($filterArr['orderTypes'])) {
                    $whereArr[] = ['order_types', '=', $filterArr['orderTypes']];
                }
                if (isset($filterArr['storeName'])) {
                    $whereArr[] = ['store_id', '=', $filterArr['storeName']];
                }
                if (isset($filterArr['payType'])) {
                    $whereArr[] = ['pay_type', '=', $filterArr['payType']];
                }
                if (isset($filterArr['orderStatus'])) {
//                    $whereArr[] = ['status', '=', $filterArr['orderStatus']];
                    $whereArr[] = ['refund_status', '=', 0];
                    $whereArr[] = ['is_del', '=', 0];
                    if($filterArr['orderStatus'] == 0){
                        $whereArr[] = ['paid', '=', 0];
                        $whereArr[] = ['status', '=', 0];
                    }elseif ($filterArr['orderStatus'] == 1){
                        $whereArr[] = ['paid', '=', 1];
                        $whereArr[] = ['status', 'in',[0,1,2,3,4]];
                        $whereArr[] = ['refund_status', 'in',[0,1,2,3]];
                    }elseif ($filterArr['orderStatus'] == 2){
                        $whereArr[] = ['paid', '=', 1];
                        $whereArr[] = ['status', '=',1];
                        $whereArr[] = ['refund_status', 'in',[0,1,2,3]];
                    }elseif ($filterArr['orderStatus'] == 3){
                        $whereArr[] = ['paid', '=', 1];
                        $whereArr[] = ['status', '=',2];
                        $whereArr[] = ['refund_status', 'in',[0,1,2,3]];
                    }elseif ($filterArr['orderStatus'] == 4){
                        $whereArr[] = ['paid', '=', 1];
                        $whereArr[] = ['status', '=',3];
                        $whereArr[] = ['refund_status', 'in',[0,1,2,3]];
                    }
                }
                if (isset($filterArr['add_time'])) {
                    $time       = explode(' - ', $filterArr['add_time']);
                    $whereArr[] = ['add_time', 'between', [strtotime($time[0]), strtotime($time[1])]];
                }
                if (isset($filterArr['buyerInfo'])) {
                    $whereu[] = ['real_name|phone|nickname' , 'like' , '%'.$filterArr['buyerInfo'].'%'];
                    $user = HtnsUser::where($whereu)->find();
                    $uid = 0;
                    if($user){
                        $uid = $user['uid'];
                    }
                    $whereArr[] = ['uid', '=', $uid];
                }
                if (isset($filterArr['receiverInfo'])) {
                    $whereArr[] = ['real_name|user_phone', 'like', '%'.$filterArr['receiverInfo'].'%'];
                }
                if (isset($filterArr['refundStatus']) && $filterArr['refundStatus']) {
                    // 根据售后状态查询售后订单
                    if($filterArr['refundStatus'] > -1){
                        $whereR['refund_type'] = $filterArr['refundStatus'];
                    }
                    $whereR['is_cancel'] = 0;
                    $whereR['is_del'] = 0;
                    $whereR['is_system_del'] = 0;
                    $whereR['is_pink_cancel'] = 0;
                    $oidArr = HtnsOrderRefund::where($whereR)->column('refund_type,store_order_id');
                    $oidRet = [];
                    // 过滤有售后订单
                    if($filterArr['refundStatus'] == -1){
                        $store_order_id = array_unique(array_column($oidArr,'store_order_id'));
                        $whereArr[] = ['id', 'not in', $store_order_id];
                    }else{
                        if($oidArr){
                            foreach ($oidArr as $v) {
                                $whereRo['store_order_id'] = $v['store_order_id'];
                                $refundType = HtnsOrderRefund::where($whereRo)->order('id desc')->value('refund_type');
                                if($refundType != $v['refund_type']){
                                    continue;
                                }
                                $oidRet[] = $v['store_order_id'];
                            }
                        }
                        $oidRet = array_unique($oidRet);
                        $whereArr[] = ['id', 'in', $oidRet];
                    }
                }
                if (isset($filterArr['product_name']) && $filterArr['product_name']) {
                    // 根据商品名称查询订单
                    $whereP[] = ['store_name' , 'like' , '%'.$filterArr['product_name'].'%'];
                    $productId = HtnsProduct::where($whereP)->column('id');
                    if($productId){
                        $whereOc[] = ['product_id' , 'in' , $productId];
                        $oidArr = HtnsOrderCartInfo::where($whereOc)->column('oid');
                        if($oidArr){
                            $whereArr[] = ['id', 'in', $oidArr];
                        }
                    }
//                    $oidArr = HtnsProduct::alias('p')->leftJoin('eb_store_order_cart_info c','c.product_id = p.id')
//                        ->where($whereP)->column('oid');
//                    var_dump($oidArr);die;
//                    if($oidArr){
//                        $whereArr[] = ['id', 'in', $oidArr];
//                    }
                }
            }
            if($storeId){
                $whereArr[] = ['store_id', '=', $storeId];
            }
            $whereArr[] = ['is_del','=',0];
            $whereArr[] = ['is_system_del','=',0];
//            halt($filter,$whereArr);
            $cacheWhereKey = 'storeOrder';
            if($export){
                $page = 1;
                $limit = 10000;
                $cacheWhere = Cache::get($cacheWhereKey);
                if(!empty($cacheWhere)){
                    $whereArr = $cacheWhere;
                }
            }else{
                if(!empty($whereArr)){
                    $resc = Cache::set($cacheWhereKey , $whereArr , 3600 * 24);
                }
            }
            $count = $this->model
                ->where($whereArr)
                ->count();
            $list  = $this->model
                ->where($whereArr)
                ->page($page, $limit)
                ->order($this->sort)
//                ->fetchSql(true)
                ->select()
                ->toArray();
            // 订单号|类型,用户昵称|ID|代理等级,商品名称,规格,购买数量,下单基站,下单时间,销售价,优惠金额,实际支付,返利积分,支付方式,订单 状态,完成时间
            $htnsUser = new HtnsUser();
            $htnsOrderRefund = new HtnsOrderRefund();
            $htnsProduct = new HtnsProduct();
            $htnsExpress = new HtnsExpress();
            $ret = [];
            foreach ($list as $v) {
                $type                  = $this->model->getOrderType($v);
                $retv['id']   = $v['id'];
                $retv['expressStatus'] = $htnsExpress->getStatus($v['id']);

                $retv['hcname']   = $htnsProduct->hcName[$v['erp_id']];
                $retv['orderSn']       = $v['order_id'] . '<br/>' . $type;
                $user                  = HtnsUser::find($v['uid']);
                $level                 = $htnsUser->getGradeName($user['jmyc_grade']);
                $retv['userInfo']      = $user['real_name'] . '|' . $v['uid'] . '|' . $level;
                $retv['productInfo']   = '';
                $retv['storeName']     = '';
                $retv['add_time']      = empty($v['add_time']) ? '' : date('Y-m-d H:i:s', $v['add_time']);
                $retv['price']         = $v['total_price'];
                $retv['pay_price']     = $v['pay_price'];
                $retv['gain_integral'] = $v['gain_integral'];
                $retv['payType']       = $this->model->getPayType($v['pay_type']);
//                $retv['orderStatus']   = $this->model->getOrderStatus($v['status'] , $v['paid']);
                $retv['orderStatus']   = $this->model->getStatus($v);
                // 查询商品详情
                $wherec['oid']     = $v['id'];
                $htnsOrderCartInfo = HtnsOrderCartInfo::where($wherec)->select()->toArray();
                $str               = '';
                foreach ($htnsOrderCartInfo as $vc) {
                    $cartInfo      = json_decode($vc['cart_info'], true);
                    $productInfo   = $cartInfo['productInfo'];
                    $attrInfo      = $cartInfo['attrInfo'];
                    $str           .= sprintf('%s|%s|%s|<br/>', $productInfo['store_name'], $attrInfo['suk'],
                        $cartInfo['truePrice'] . 'x' . $cartInfo['cart_num']);
//                    $retv['price'] += $cartInfo['sum_price'];
                }
                $retv['productInfo']     = $str;
                $retv['deduction_price'] = bcsub($retv['price'], $retv['pay_price'], 2);
                // 下单基站
                $store = HtnsBasestationStore::find($v['store_id']);
                if ($store) {
                    $retv['storeName'] = $store['name'];
                }
                $retv['buyerInfo'] = $user['real_name'].'-'.$user['phone'];// 买家信息
                $retv['receiverInfo'] = $v['real_name'].'-'.$v['user_phone'];// 收货人信息
                $refundStatus = $htnsOrderRefund->getOrderRefundStatus($v['id']);
                $retv['refundStatus'] = $refundStatus;
                $retv['orderTypes']       = $this->model->getOrderTypes($v['order_types']);
                $ret[] = $retv;
            }
            $list = $ret;
            // 导出
            if($export){
                return $list;
            }
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
//        $this->assign('tabVal',$tabVal);
        $row['waitPay'] = $this->model->getWaitPayNum();
        $row['waitReceived'] = $this->model->getWaitReceivedNum();
        $row['waitDeliver'] = $this->model->getWaitDeliverNum();
        $row['Completed'] = $this->model->getCompletedNum();
        $this->assign('row',$row);
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="导出")
     */
    public function export()
    {

//        list($page, $limit, $where) = $this->buildTableParames();
//        $tableName = 'mall_cate';
////        $tableName = CommonTool::humpToLine(lcfirst($tableName));
//        $prefix = config('database.connections.mysql.prefix');
//        $dbList = \think\facade\Db::query("show full columns from {$prefix}{$tableName}");
//        $header = [];
//        foreach ($dbList as $vo) {
//            $comment = !empty($vo['Comment']) ? $vo['Comment'] : $vo['Field'];
//            if (!in_array($vo['Field'], $this->noExportFields)) {
//                $header[] = [$comment, $vo['Field']];
//            }
//        }


        $header = [
            ['订单Id','id'],
            ['发货仓库','hcname'],
            ['订单类型','orderTypes'],
            ['订单号|类型','orderSn'],
            ['用户昵称|ID|代理等级','userInfo'],
            ['商品信息','productInfo'],
            ['商品名称','productName'],
            ['商品规格','productAttr'],
            ['商品数量','productNum'],
            ['商品售价','productPrice'],
            ['下单基站','storeName'],
            ['下单时间','add_time'],
            ['销售价','price'],
            ['优惠金额','deduction_price'],
            ['实际支付','pay_price'],
            ['返利积分','gain_integral'],
            ['支付方式','payType'],
            ['订单状态','orderStatus'],
            ['物流状态','expressStatus'],
            ['买家信息','buyerInfo'],
            ['收货人信息','receiverInfo'],
            ['售后状态','refundStatus'],
        ];
        // 根据商品拆分数据再进行合并
        $list = $this->index(1);
        $ret = [];
        // 订单多个商品数据合并处理
        $hh = '<br/>';
        foreach ($list as $v) {
            $v['orderSn'] = str_replace($hh,'',$v['orderSn']);
            $v['productInfo'] = rtrim($v['productInfo'] , $hh);
            $productArr = explode($hh , $v['productInfo']);

            $retv = $v;
            $retv['is_merge'] = 0;
            if(count($productArr) > 1){
                foreach ($productArr as $kp => $vp) {
                    $retv['productInfo'] = $vp;
                    $productInfoArr = explode('|',$vp);
                    $retv['productName'] = $productInfoArr[0];
                    $retv['productAttr'] = $productInfoArr[1];
                    $priceInfo = explode('x',$productInfoArr[2]);
                    $retv['productPrice'] = $priceInfo[0];
                    $retv['productNum'] = $priceInfo[1];
                    $retv['is_merge'] = 0;
                    if($kp == 0){
                        $retv['is_merge'] = 1;// 第一行合并,其它行默认
                    }
                    $ret[] = $retv;
                }
            }else{
                $productInfoArr = explode('|',$v['productInfo']);
                $retv['productName'] = $productInfoArr[0];
                $retv['productAttr'] = $productInfoArr[1];
                $priceInfo = explode('x',$productInfoArr[2]);
                $retv['productPrice'] = $priceInfo[0];
                $retv['productNum'] = $priceInfo[1];
                $ret[] = $retv;
            }

//            if($productArr && count($productArr) > 1){
//                foreach ($productArr as $kp => $vp) {
//                    foreach ($list as $vl) {
//                        $retv = $vl;
//                        $retv['is_merge'] = 0;
//                        $retv['productInfo'] = $vp;
//                        $productInfoArr = explode('|',$vp);
//                        $retv['productName'] = $productInfoArr[0];
//                        $retv['productAttr'] = $productInfoArr[1];
//                        $priceInfo = explode('x',$productInfoArr[2]);
//                        $retv['productPrice'] = $priceInfo[0];
//                        $retv['productNum'] = $priceInfo[1];
//
//                        if($kp == 0){
//                            $retv['is_merge'] = 1;// 第一行合并,其它行默认
//                        }
//                        $ret[] = $retv;
//                    }
//                }
//            }else{
//                $retv = $v;
//                $retv['is_merge'] = 0;
//                $ret[] = $retv;
//            }
        }
        if($ret){
            $list = $ret;
        }
//        halt($ret);
//        halt($list);
        $fileName = time();
        $arrA = ['A','B','C','D','E','F'];
        $arrB = ['K','L','M','N','O','P','Q','R','S','T','U','V'];
        return Excel::exportData($list, $header, $fileName, 'xlsx','',[],$arrA,$arrB);
    }

    /**
     * @NodeAnotation(title="订单详情")
     */
    public function detail($id)
    {
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');
        $rest['order'] = $row->toArray();
        if($rest['order']['add_time']){
            $rest['order']['add_time'] = date('Y-m-d H:i:s',$rest['order']['add_time']);
        }
        $user                  = HtnsUser::find($row['uid']);
        $rest['order']['buyer'] = $user;
        $type = $this->model->getOrderType($rest['order']);
        if($type){
            $rest['order']['orderType'] = $type;
        }
        $rest['order']['payType']       = $this->model->getPayType($row['pay_type']);
        $rest['order']['orderStatus']   = $this->model->getStatus($rest['order']);
        $htnsOrderRefund = new HtnsOrderRefund();
        $refundStatus = $htnsOrderRefund->getOrderRefundStatus($rest['order']);
        $rest['order']['refundStatus'] = $refundStatus;

        // 查询提交订单时间.买家付款时间.卖家发货时间.买家收货时间
        $time['addTime'] = $rest['order']['add_time'] ;
        $time['payTime'] = $rest['order']['pay_time'] ? date('Y-m-d H:i:s',$rest['order']['pay_time']) : '' ;

        $htnsOrderStatus = new HtnsOrderStatus();
        $time['deliveryTime'] = '' ;
        $htnsOrderStatusRow = $htnsOrderStatus->getRow($id , 'delivery_goods');
        if($htnsOrderStatusRow){
            $time['deliveryTime'] = $htnsOrderStatusRow['change_time'];
        }

        $htnsOrderStatus = new HtnsOrderStatus();
        $rest['order']['statusListLog'] = [];

        $orderService = new OrderService();
        $statusList = $orderService->orderLogMerge($id);
        $rest['order']['statusListLog'] = $statusList;
//        $whereS['oid'] = $id;
//        $statusList = HtnsOrderStatus::where($whereS)->order('change_time desc')->select()->toArray();
//        if($statusList){
//            foreach ($statusList as $k => $v) {
//                $statusList[$k]['change_time'] = $v['change_time'] ? date('Y-m-d H:i:s',$v['change_time']) : '';
//            }
//            $rest['order']['statusListLog'] = $statusList;
//        }
//        halt($rest['order']['statusListLog']);
        $time['takeDeliveryTime'] = '' ;
        $htnsOrderStatusRow = $htnsOrderStatus->getRow($id , 'take_delivery');
        if($htnsOrderStatusRow){
            $time['takeDeliveryTime'] = $htnsOrderStatusRow['change_time'];
        }
        $rest['order']['payTime'] = $time['payTime'];
        $rest['order']['deliveryTime'] = $time['deliveryTime'];
        $rest['order']['takeDeliveryTime'] = $time['takeDeliveryTime'];

        // 查询原系统订单详情接口
        $domain = sysconfig('other','domain');// 域名

        $wherec['oid'] = $row['id'];
        $htnsOrderCartInfo = HtnsOrderCartInfo::where($wherec)->select()->toArray();
        $orderCartInfoService = new OrderCartInfoService();
        $goods = [];
        $rest['trueSumPrice'] = 0;
        foreach ($htnsOrderCartInfo as $vc) {
            $cartInfo = json_decode($vc['cart_info'],true);
            $good = $orderCartInfoService->getProductDetail($cartInfo , $row);
            $rest['trueSumPrice'] += $good['true_sum_price'];
            $goods[] = $good;
        }
        $rest['order']['goods'] = $goods;
//        halt($rest['order']['goods']);
//        $rest['order']['goods'] = $orderCartInfoService->getProductDetail($rest['orderInfo']['cartInfo'] , $row);
        // 查询物流信息
        $rest['express'] = [];
        $rest['expressStatu'] = '';
        $rest['shStatu'] = '';
        if($row['delivery_id']){
            $kdiKey = 'kd1'.$id;
            $kdData = Cache::get($kdiKey);
            if($kdData){
                $expressData = $kdData;
//                halt('cache',$expressData);
            }else{
                $kdurls          = $domain.'/api/kdi?no=' . $row['delivery_id'].'&type='.$row['delivery_code'];
                $expressData    = $this->httpCurlGet($kdurls, 1);
                Cache::set($kdiKey , $expressData , 3600);
            }
            $expressDataArr = json_decode($expressData, true);
//        halt($cacheDataToken,$token,$header,$expressDataArr);
            if ($expressDataArr['status'] == 200) {
                $deliveryData = $expressDataArr['data'];
                if($deliveryData['list']){
                    $rest['expressStatu'] = '已发货';
                }
                if($deliveryData['issign']){
                    $rest['expressStatu'] = '已签收';
                }
                $rest['express'] = $deliveryData['list'];
            }
            // 快递已签收,订单状态未签收
            if($rest['expressStatu'] == '已签收' && $row['status']!=2){
                // 调用接口收货
//                $shurls          = $domain.'/adminapi/order/take/' . $id;
//                $shData    = $this->httpCurlGet($shurls, 1, $header , 'PUT');
                $shurls          = $domain.'/api/jizhan/take/' . $id;
                $shData    = $this->httpCurlPost($shurls);
                $shDataArr = json_decode($shData, true);
//            halt($shurls,$shDataArr);
                if ($shDataArr['status'] == 200) {
                    $rest['shStatu'] = 'POST方法收货成功';
                }
            }
        }
        // http://www.dameiliuhe.com/adminapi/jizhan/order/info/637
//        halt($rest);
        $this->assign('row', $rest);
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="订单操作")
     */
    public function deal($id)
    {
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');

//        $row['type'] = 0;
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);
            try {
                // 修改备注信息
                if($post['remark']){
                    $row['remark'] = $post['remark'];
                    $row->save();
                }
                $htnsApiService = new HtnsApiService();
                // 发货
                if($post['type'] == 1){
                    $where['name'] = $post['delivery_name'];
                    $delivery_code = HtnsExpress::where($where)->value('code');
                    $res = $htnsApiService->updateDelivery($row['id'] , $post['delivery_name'],$post['delivery_id'],$delivery_code);
                    if($res['code']){
                        $this->success('发货成功');
                    }else{
                        $this->error('发货失败,'.$res['msg']);
                    }
                }elseif ($post['type'] == 2){
                    // 确认收货
                    $res = $htnsApiService->takeOrder($row['id']);
//                    var_dump($res);die;
                    if($res['code']){
                        $this->success('发货成功');
                    }else{
                        $this->error('发货失败,'.$res['msg']);
                    }
                }
            } catch (Exception $e) {
                $this->error('操作失败,'.$e->getMessage());
            }
        }
        $this->assign('row', $row);
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="快递公司列表")
     */
    public function getExpressList()
    {
        $ret['code'] = 1;
        $ret['msg']  = '获取成功';
        $ret['data'] = [];

        $htnsExpress = new HtnsExpress();
        $res            = $htnsExpress->getList();
        if ($res) {
            foreach ($res as &$v) {
                $v['express'] = $v['name'] . '-' . $v['code'];
            }
            $ret['data'] = $res;
        }
        return json($ret);
    }
}